package com.opentool.dns;
import com.opentool.web.service.ILocalDnsService;
import com.opentool.web.spring.SpringUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.dns.*;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class DnsHandler extends SimpleChannelInboundHandler<DatagramDnsQuery> {

    private DnsProxy dnsProxy;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ILocalDnsService localDnsService=SpringUtil.getBean(ILocalDnsService.class);
        String dnsServer=localDnsService.queryDnsServer();
        super.channelActive(ctx);
        this.dnsProxy=new DnsProxy();
        this.dnsProxy.init(dnsServer,53,dnsProxy,ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramDnsQuery query) throws Exception {
            this.dnsProxy.setClientSender(query.sender());
            this.dnsProxy.setClientRecipient(query.recipient());
            DefaultDnsQuestion dnsQuestion = query.recordAt(DnsSection.QUESTION);
            log.info("查询的域名：{},ID:{}",dnsQuestion.name(),query.id());
            ILocalDnsService localDnsService=SpringUtil.getBean(ILocalDnsService.class);
            byte[] dnsRecord=localDnsService.dnsResolver(dnsQuestion.name(),query.recipient().getAddress().getHostAddress());
            if(dnsRecord[0]!=0){
                DatagramDnsResponse response = new DatagramDnsResponse(query.recipient(), query.sender(), query.id());
                response.setId(query.id());
                response.addRecord(DnsSection.QUESTION, dnsQuestion);
                ByteBuf buf=ctx.channel().alloc().buffer().writeBytes(dnsRecord);
                DefaultDnsRawRecord queryAnswer = new DefaultDnsRawRecord(dnsQuestion.name(), DnsRecordType.A, 10, buf);
                response.addRecord(DnsSection.ANSWER, queryAnswer);
                ctx.writeAndFlush(response);
            }else{
                this.dnsProxy.sendDnsQuery(query);
            }
    }

}
